package timbap.artwork.storage;

import org.apache.commons.io.IOUtils;
import timbap.artwork.util.HttpGetBufferRegistry;
import timbap.visualizer.api.model.PlaylistEntry;
import timbap.visualizer.impl.context.textures.AbstractP5TextureCacheManager;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class ResultStorageManager {

    private static ResultStorageManager INSTANCE;

    public boolean writeToTempDir(InputStream pInputStream, PlaylistEntry pPlaylistEntry, int pImageIndex) {
        boolean tSuccess = false;
        String tFileName = getTempArtworkFilename(pPlaylistEntry, pImageIndex);
        try {
            OutputStream tTempFileOutput = new FileOutputStream(tFileName);
            IOUtils.copy(pInputStream, tTempFileOutput);
            tSuccess = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            HttpGetBufferRegistry.getInstance().release(pInputStream);
        }
        return tSuccess;
    }

    public boolean writeArtworkFile(InputStream pInputStream, PlaylistEntry pPlaylistEntry) {
        boolean tSuccess = false;
        File tArtworkFile = AbstractP5TextureCacheManager.findOrCreateArtworkFile(pPlaylistEntry, ".jpg");
        OutputStream tTempFileOutput = null;
        try {
            tTempFileOutput = new FileOutputStream(tArtworkFile);
            IOUtils.copy(pInputStream, tTempFileOutput);
            tSuccess = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (tTempFileOutput != null) {
                try {
                    tTempFileOutput.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            HttpGetBufferRegistry.getInstance().release(pInputStream);
        }
        return tSuccess;
    }

    public InputStream loadFromTempDir(PlaylistEntry pPlaylistEntry, int pImageIndex) {
        InputStream tInputStream = null;
        String tFileName = getTempArtworkFilename(pPlaylistEntry, pImageIndex);
        try {
            tInputStream = new FileInputStream(tFileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return tInputStream;
    }


    private String getTempArtworkFilename(PlaylistEntry pPlaylistEntry, int pImageIndex) {
        return "temp/" + pPlaylistEntry.getAudioFile().getAbsolutePath().hashCode() + "" + pImageIndex + ".jpg";
    }

    public static ResultStorageManager getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new ResultStorageManager();
        }
        return INSTANCE;
    }
}
